# -*- encoding=utf8 -*-
__author__ = "Administrator"

from airtest.core.api import *

from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import pymysql
import time
import random
import sys, io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)

auto_setup(__file__)

# 定义区配置定义区配置定义区配置##############################

# 关键字
keywords = "ipad"
# 表单后缀
form_keywords = "ipad"

# 滑动次数
swipetimes = 12

# 翻页起始点
starpoint = (200, 1900)
endpoint = (200, 570)

# 打开数据库连接
db = pymysql.connect("127.0.0.1", "root", "123456", "xianyu", charset='utf8mb4')

# 循环起点
var1 = 1

# 循环终点
loopend = 10000

# 定义区配置定义区配置定义区配置#######################
# 数据定义区


# db = pymysql.connect("39.108.86.206", "root", "123456", "xianyu", charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()


# 数据库查询操作方法

# 根据pah获取元素
# filter_panel = poco(name="android.widget.FrameLayout")
# f_letter = get_ui_obj(filter_panel, [0,0,0,0,3,0,2])
# print( f_letter.get_text())
def get_ui_obj(parent, path):
    try:
        chd = parent.child()
        # print("chd,", chd.get_text(),chd.get_name(),chd.get_position())
        if len(path) > 1:
            # print( "path[0]",path[0],path[1:])
            return get_ui_obj(chd[path[0]], path[1:])
        else:
            return chd[path[0]]
    except:
        print("error")
        return 0


# 数据库插入操作方法
def dosql(sql):
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
        print("sql ok")
    except:
        # Rollback in case there is any error
        db.rollback()
        print("sql error")
        print(sql)


# 查询数据
def findgoods(title):
    sql = "SELECT id,detail FROM goods_ipad WHERE titile = '%s' and   create_time>= now()-interval 1 day"
    data = (title,)
    cursor.execute(sql % data)
    # for row in cursor.fetchall():
    #     print("Name:%s\tSaving:%s" % row)
    # print('共查找出', cursor.rowcount, '条数据')
    return cursor.rowcount


# 查找关键词list
def findallkeywords():
    form = "keyword_" + form_keywords
    cursor.execute('select keyword from ' + form)
    rs = cursor.fetchall()
    result_list = []
    for record in rs:
        result_list.append(record[0])
    return result_list


# 数据库插入操作方法
def insertgoods(title, tags):
    now = time.strftime("%Y-%m-%d %H:%M:%S")
    # SQL 插入语句
    # sql = "INSERT INTO `goods_ipad` (`titile`, `detail`, `price`, `province`, `city`,result_tag) VALUES (",title,"', '",title,"', 20, '广东', '广州','",tags,"','",now,"') "
    # 根据title拆分数据 title price province wantpeople
    listparmters = title.split('\n')
    # for value in listparmters:	# 循环输出列表值
    #    print ("listparmters",value)
    # 价格
    price = listparmters[2]
    # 标题
    titlestring = listparmters[0]
    # 省份
    province = listparmters[-1]
    # 想要人数
    wantpeople = listparmters[-2].replace('人想要', '')
    # 价格过低
    if ("闲鱼币" in price or float(price) < 100):
        tags = "虚假商品"
    sql = "INSERT INTO `goods_" + form_keywords + "` (`titile`, `price`, `province`,result_tag,create_time,wantpeople) VALUES ('" + titlestring + "' ," + price + ", '" + province + "','" + tags + "','" + now + "'," + wantpeople + ") "
    # print(sql)
    dosql(sql)


mykeylist = findallkeywords()


# 是否包含数组关键词方法
def findifcontain(stringcontent):
    for i in mykeylist:
        # print("i: ", i)
        if i in stringcontent:
            return 1
    return 0


# 获取淘口令
def gettaocode():
    # 点击更多
    poco(text="更多").click()
    # 点击淘口令
    poco(text="淘口令").click()
    # 获取淘口令
    taokouling = poco(name="com.taobao.idlefish:id/tvWarnDetail", type="android.widget.TextView").get_text();
    # 点击返回
    keyevent("BACK")
    return taokouling


# 从搜索页面进入详情页面判断是否商家
def findifbad(title):
    sleep(1.0)
    listparmters = title.split('\n')
    # 价格
    price = listparmters[2]
    # 数据库标题
    titlestring = listparmters[0]
    # 省份
    province = listparmters[-1]
    # 进入详情页
    poco(text=title).click()
    # 获取详细描述
    filter_panel = poco(name="android.widget.FrameLayout")

    deataildom = get_ui_obj(filter_panel, [0, 0, 0, 0, 3, 0, 2])
    if (not deataildom):
        deataildom = get_ui_obj(filter_panel, [0, 0, 0, 0, 2, 0, 2])
    # 细节描述
    detail = deataildom.get_text()
    detail = pymysql.escape_string(detail)
    # 判断细节描述 跟新虚假信息
    if (findifcontain(detail)):
        # 虚假信息，进行跟新
        updatesql = "update goods_" + form_keywords + " set detail ='" + detail + "', result_tag='虚假商品' where titile= '" + titlestring + "' and province ='" + province + "' and  create_time>= now()-interval 1 day "
        dosql(updatesql)
    else:
        # 补充相关信息
        # taokouling=gettaocode()
        # taokouling=pymysql.escape_string(taokouling)
        # taokouling=taokouling.replace("'","\\\'")
        # taokouling=taokouling.replace('"','\\\"')
        # updatesql="update goods_"+form_keywords+" set detail ='"+detail+"', result_tag='真实商品' , goodstaokouling='"+taokouling+"' where titile= '"+titlestring+ "' and province ='"+province+"' and  create_time>= now()-interval 1 day "
        updatesql = "update goods_" + form_keywords + " set detail ='" + detail + "', result_tag='真实商品'  where titile= '" + titlestring + "' and province ='" + province + "' and  create_time>= now()-interval 1 day "
        # dosql(updatesql)
        try:
            # 执行sql语句
            cursor.execute(updatesql)
            # 提交到数据库执行
            db.commit()
            print("sql ok")
        except:
            # Rollback in case there is any error
            print("sql error")
            print(updatesql)
    # print("detail"+detail)
    # 返回搜索结果页
    poco(text="返回").click()

    # 获取卖家名称
    # 获取商品详情


# 储存数据到 mysql


def openxianyu():
    # 关闭闲鱼
    stop_app("com.taobao.idlefish")
    # 打开闲鱼
    start_app("com.taobao.idlefish")
    sleep(0.5)
    # 点击搜索栏
    poco(name="com.taobao.idlefish:id/search_bg_img_front").click()
    sleep(0.5)
    # 输入文字搜索
    poco(name="com.taobao.idlefish:id/search_term").set_text(keywords)
    sleep(1.0)
    # 点击搜索按钮
    poco(name="com.taobao.idlefish:id/search_button").click()

    # 点击综合
    poco(text="已折叠, 综合").click()
    # 点击最新发布
    poco(text="最新发布").click()
    # 获取标题 翻页
    buttonwordslist = ["信用", "区域", "筛选", "细选"]
    # 商品临时列表
    tempgoodslist = []
    swipetimes = 9
    count = 0
    while (count < swipetimes):
        sleep(1.0)
        for i in poco(name="android.widget.ScrollView").child(name="android.view.View"):
            detail = i.get_text()
            ifindatabase = findgoods(detail.split('\n')[0])
            # 排除搜索页
            if (detail not in buttonwordslist and detail not in tempgoodslist and ifindatabase < 1):
                # 添加到tempgoodslist中
                tempgoodslist.append(detail)
                # 进行关键词过滤tempgoodslist
                if (findifcontain(detail)):
                    print("虚假商品")
                    # 插入数据库中
                    insertgoods(detail, "虚假商品")
                else:
                    insertgoods(detail, "真实商品")
                    findifbad(detail)
                    print("真实商品")

        count = count + 1
        swipe(starpoint, endpoint)
    print("--结束")
    # 循环
    # 关键词过滤
    # 关闭闲鱼
    stop_app("com.taobao.idlefish")
    sleep(random.randint(100, 300))


while (var1 < loopend):
    try:
        openxianyu()
    except:
        print("d")
        # Rollback in case there is any error
    var1 = var1 + 1

# 关闭数据库连接
db.close()
